<?php

namespace app\admin\controller;

use app\common\controller\AdminController;
use EasyAdmin\annotation\ControllerAnnotation;
use EasyAdmin\annotation\NodeAnotation;
use think\App;
use think\facade\Db;
use dh2y\qrcode\QRcode;

/**
 * @ControllerAnnotation(title="商户列表")
 */
class Merchant extends AdminController
{

    use \app\admin\traits\Curd;

    public function __construct(App $app)
    {
        parent::__construct($app);

        $this->model = new \app\admin\model\Merchant();
        
    }

     /**
     * @NodeAnotation(title="列表")
     */
    public function index()
    {
        if ($this->request->isAjax()) {
            list($page, $limit, $where) = $this->buildTableParames();
            $count = $this->model
                ->where($where)
                ->count();
            $list = $this->model
                ->where($where)
                ->page($page, $limit)
                ->order($this->sort)
                ->select();
                foreach ($list as $k => $v){
                    //地区
                    if(!empty($v['province'])){
                        $province = Db::name('area')->where('id',$v['province'])->field('name')->find();
                    }else{
                        $province['name'] = "";
                    }

                    if(!empty($v['city'])){
                        $city = Db::name('area')->where('id',$v['city'])->field('name')->find();
                    }else{
                        $city['name'] = "";
                    }

                    if(!empty($v['area'])){
                        $area = Db::name('area')->where('id',$v['area'])->field('name')->find();
                    }else{
                        $area['name'] = "";
                    }
 
                    $v['position'] = $province['name'].$city['name'].$area['name'].$v["address"];
                    $list[$k] = $v;
                }
            $data = [
                'code'  => 0,
                'msg'   => '',
                'count' => $count,
                'data'  => $list,
            ];
            return json($data);
        }
        return $this->fetch();
    }


    /**
    * @NodeAnotation(title="添加")
    */
    public function add()
    {
        if ($this->request->isAjax()) {
            $post = $this->request->param();
            if(empty($post['merchant_name'])){
                $this->error('商户名称不能为空');
            }
            $flag = Db::name('merchant')->where("merchant_name",$post["merchant_name"])->find();
            if(!empty($flag)){
                $this->error('商户名称已存在，请重新输入');
            }
            $data = [
                'merchant_name'=>$post['merchant_name'],
                'main_image'=>$post['image'],
                'carousel_chart'=>$post['logo'],
                'phone'=>$post['phone'],
                'province'=>$post['province'],
                'city'=>$post['city'],
                'area'=>$post['area'],
                'address'=>$post['address'],
                'longitude'=>$post['longitude'],
                'latitude'=>$post['latitude'],
                'label'=>$post['label'],
                'desc'=>$post['desc'],
                'create_time'=>time()
            ];
            try {
                Db::name('merchant')->insert($data); 
                $mid = Db::name('merchant')->getLastInsID();
                //生成H5二维码
                $qrcode = $this->createQrcode($mid);
                Db::name('merchant')->where("id",$mid)->update(["qrcode"=>$qrcode]);

            } catch (\Exception $e) {
                $this->error('保存失败:' . $e->getMessage());
            }
            $this->success('保存成功');
        }else{
            $province = Db::name("area")->where('level', 0)->select()->toArray();
            $this->assign("province",$province);
            return $this->fetch();
        }
        
    }

    //生成H5二维码
    public function createQrcode($mid)
    {
        $code = new QRcode();
        //$res = $code->png('https://www.baidu.com/',false, 6)->logo('logo.png')->entry();
        $res = $code->png('https://yq.xianmeta.com/peiwan/#/pages/index/index?mid='.$mid,false, 10)->entry();
        return $res;
    }

     /**
    * @NodeAnotation(title="编辑")
    */
    public function edit()
    {
        if ($this->request->isAjax()) {
            $post = $this->request->param();
            if(empty($post['merchant_name'])){
                $this->error('商户名称不能为空');
            }
            $data = [
                'merchant_name'=>$post['merchant_name'],
                'main_image'=>$post['image'],
                'carousel_chart'=>$post['logo'],
                'phone'=>$post['phone'],
                'province'=>$post['province'],
                'city'=>$post['city'],
                'area'=>$post['area'],
                'address'=>$post['address'],
                'longitude'=>$post['longitude'],
                'latitude'=>$post['latitude'],
                'label'=>$post['label'],
                'desc'=>$post['desc']
            ];
            try {
               $this->model->where('id',$post['id'])->update($data);
             
            } catch (\Exception $e) {
                $this->error('保存失败:' . $e->getMessage());
            }
            $this->success('保存成功') ;
        }else{
            $post = $this->request->param(); 
            $row = $this->model->where('id',$post['id'])->find();
            $province = Db::name("area")->where('level', 0)->select()->toArray();
            $this->assign("province",$province);

            $city = Db::name("area")->where('pid', $row["province"])->select()->toArray();
            $this->assign("city",$city);

            $area = Db::name("area")->where('pid', $row["city"])->select()->toArray();
            $this->assign("area",$area);
            $row['desc'] = html_entity_decode($row['desc']);
            $row['desc'] = str_replace(array("\r", "\n\n", "\s", "\t", "\n"), '<br/>', $row['desc']);

            $this->assign('row', $row); 
            return $this->fetch();
        }
       
    }

    
    public function province(){
        if ($this->request->isAjax()) {
            $brand_id = $this->request->param('id');
            $list = Db::name("area")->where('pid', $brand_id)->select()->toArray();
            $opt = "<option value=''>--请选择--</option>";
            foreach ($list as $k => $val) {
                $opt .= "<option value='{$val['id']}'>{$val['name']}</option>";
            }
            if ($opt) {
                exit(json_encode(array('opt' => $opt)));
            } else {
                exit(json_encode(array('status' => 1)));
            }
        }
    }

    public function city(){
        if ($this->request->isAjax()) {
            $brand_id = $this->request->param('id');
            $list = Db::name("area")->where('pid', $brand_id)->select()->toArray();
            $opt = "<option value=''>--请选择--</option>";
            foreach ($list as $k => $val) {
                $opt .= "<option value='{$val['id']}'>{$val['name']}</option>";
            }
            if ($opt) {
                exit(json_encode(array('opt' => $opt)));
            } else {
                exit(json_encode(array('status' => 1)));
            }
        }
    }
    
    
}